import React from 'react';
import { connect } from 'react-redux'
import { messages } from "share/common";
import { Button, Modal } from "antd"

import SlideFrame from 'components/slide-frame'
import BatchApportion from 'containers/expense-report/components/slide-frame-batch-apportion'
import Condition from 'components/condition'
const { If } = Condition;

class ButtonBatchApportion extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      slideFrameVisible: false,
      invoices: [],
    }
  }

  handleClick = () => {
    const { invoiceList, rowSelection } = this.props;
    let invoices = [];
    if (this.checkHasInvoice()) {
      rowSelection.selectedRowKeys.map(key => {
        invoiceList.map(item => {
          if (item.invoiceOID === key) {
            invoices.push(item)
          }
        })
      });
      this.checkSameCurrency(invoices)
    }
  };

  // 检查是否已选择了费用
  checkHasInvoice = () => {
    const { rowSelection } = this.props;
    if (!rowSelection.selectedRowKeys || rowSelection.selectedRowKeys.length === 0) {
      Modal.info({
        title: messages('expense-parent-report.key219')/*请先勾选费用！*/
      });
      return false;
    }
    return true;
  };

  // 检查币种是否一致
  checkSameCurrency = (invoices) => {
    let currencyCode = invoices[0].invoiceView.currencyCode;
    let currencyIsSame = true;
    invoices.map(item => {
      item.invoiceView.currencyCode !== currencyCode && (currencyIsSame = false)
    });
    if (!currencyIsSame) {
      Modal.info({
        title: messages('expense-parent-report.key220')/*勾选费用的币种须一致！*/
      });
      return false;
    }
    this.checkAmountIsNotZero(invoices);
  };

  // 检查费用金额是否都不为0
  checkAmountIsNotZero = (invoices) => {
    // 存在金额为0的费用
    if (invoices.some(item => Number(item.invoiceView.amount) === 0)) {
      Modal.confirm({
        title: (
          <div>
            <div>{messages('expense-parent-report.key221')/*金额为0的费用不能分摊！*/}</div>
            <div>
              <span style={{color: '#f5222d'}}>{messages('expense-parent-report.key222')/*将为你自动取消勾选金额为0的费用！*/}</span>
              {messages('expense-parent-report.key223')/*是否继续？*/}
            </div>
          </div>
        ),
        okText: messages('expense-parent-report.key224')/*继续*/,
        onOk: () => this.cancelZeroAmount(invoices)
      });
      return false;
    }
    this.checkSameSymbolAmount(invoices);
  };

  // 检查金额符号是否一致
  checkSameSymbolAmount = (invoices) => {
    // 金额为正数 (>0)
    let amountIsPositive = true;
    let symbolIsSame = true;
    for (let i = 0; i < invoices.length; i++) {
      // 不考虑金额为0的符号
      if (invoices[i].invoiceView.amount !== 0) {
        amountIsPositive = invoices[i].invoiceView.amount > 0
      }
    }
    invoices.map(item => {
      if (item.invoiceView.amount !== 0) {
        let itemAmountIsPositive = item.invoiceView.amount > 0;
        itemAmountIsPositive !== amountIsPositive && (symbolIsSame = false)
      }
    });
    // 存在金额符号不一致的费用（有正有负）
    if (!symbolIsSame) {
      Modal.confirm({
        title: (
          <div>
            <div>{messages('expense-parent-report.key225')/*勾选费用的符号必须一致！*/}</div>
            <div>
              <span style={{color: '#f5222d'}}>{messages('expense-parent-report.key226')/*将为你自动取消勾选负数费用！*/}</span>
              {messages('expense-parent-report.key223')/*是否继续？*/}
            </div>
          </div>
        ),
        okText: messages('expense-parent-report.key224')/*继续*/,
        onOk: () => this.cancelNegativeAmount(invoices)
      });
      return false;
    }
    this.checkApportionUsed(invoices);
  };

  // 检查费用是否开启分摊
  checkApportionUsed = (invoices) => {
    let allApportionUsed = true;
    invoices.map(item => {
      !item.invoiceView.apportionUsed && (allApportionUsed = false)
    });
    // 存在没开启分摊的费用
    if (!allApportionUsed) {
      Modal.confirm({
        title: (
          <div>
            <div>{messages('expense-parent-report.key227')/*勾选费用须开启分摊！*/}</div>
            <div>
              <span style={{color: '#f5222d'}}>{messages('expense-parent-report.key228')/*将为你自动取消未开启分摊的费用！*/}</span>
              {messages('expense-parent-report.key223')/*是否继续？*/}
            </div>
          </div>
        ),
        okText: messages('expense-parent-report.key224')/*继续*/,
        onOk: () => this.cancelApportionUnused(invoices)
      });
      return false;
    }
    this.setState({ invoices }, () => {
      this.setState({ slideFrameVisible: true })
    });
  };

  // 取消勾选金额为0的费用
  cancelZeroAmount = (invoices) => {
    let { rowSelection } = this.props;
    let selectedInvoices = [];
    let selectedRowKeys = [];
    invoices.map(item => {
      if (Number(item.invoiceView.amount) !== 0) {
        selectedInvoices.push(item);
        selectedRowKeys.push(item.invoiceView.invoiceOID)
      }
    });
    // 没有开启分摊的费用
    if (selectedInvoices.length === 0) {
      Modal.info({
        title: messages('expense-parent-report.key219')/*请先勾选费用！*/
      })
    } else {
      this.checkSameSymbolAmount(selectedInvoices);
    }
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.props.expenseRowSelect(rowSelection);
  };

  // 取消勾选负数费用
  cancelNegativeAmount = (invoices) => {
    let { rowSelection } = this.props;
    let selectedInvoices = [];
    let selectedRowKeys = [];
    invoices.map(item => {
      if (item.invoiceView.amount > 0) {
        selectedInvoices.push(item);
        selectedRowKeys.push(item.invoiceView.invoiceOID)
      }
    });
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.props.expenseRowSelect(rowSelection);
    this.checkApportionUsed(selectedInvoices);
  };

  // 取消勾选没开启分摊的费用
  cancelApportionUnused = (invoices) => {
    let { rowSelection } = this.props;
    let selectedInvoices = [];
    let selectedRowKeys = [];
    invoices.map(item => {
      if (item.invoiceView.apportionUsed) {
        selectedInvoices.push(item);
        selectedRowKeys.push(item.invoiceView.invoiceOID)
      }
    });
    // 没有开启分摊的费用
    if (selectedInvoices.length === 0) {
      Modal.info({
        title: messages('expense-parent-report.key219')/*请先勾选费用！*/
      })
    } else {
      this.setState({ invoices: selectedInvoices }, () => {
        this.setState({ slideFrameVisible: true })
      })
    }
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.props.expenseRowSelect(rowSelection);
  };

  render() {
    const { batchApportion, expenseReport, costCenterItemsApportion } = this.props;
    const { slideFrameVisible, invoices } = this.state;
    return (
      <If value={batchApportion}>
        <Button onClick={this.handleClick}>
          {messages('expense-parent-report.key229')/*批量分摊*/}
        </Button>
        <section className="batch-apportion">
          <SlideFrame
            show={slideFrameVisible}
            title={messages('expense-parent-report.key229')/*批量分摊*/}
            content={BatchApportion}
            params={{
              slideFrameVisible,
              invoices,
              expenseReport,
              costCenterItemsApportion
            }}
            onClose={() => this.setState({ slideFrameVisible: false })}
            afterClose={() => this.setState({ slideFrameVisible: false })}
          />
        </section>
      </If>
    )
  }
}

ButtonBatchApportion.propTypes = {
  batchApportion: React.PropTypes.bool, //开启批量分摊
  invoiceList: React.PropTypes.array,
  rowSelection: React.PropTypes.object,
  expenseReport: React.PropTypes.object, //报销单详情
  costCenterItemsApportion: React.PropTypes.array, //参与分摊的成本中心
  expenseRowSelect: React.PropTypes.func,
};

function mapStateToProps(state) {
  return { }
}

export default connect(mapStateToProps)(ButtonBatchApportion)
